package com.whoisaa.wifitransfer.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.whoisaa.wifitransfer.IServerConnectionListener;
import com.whoisaa.wifitransfer.R;
import com.whoisaa.wifitransfer.WifiServerThread;
import com.whoisaa.wifitransfer.WifiTools;
import com.whoisaa.wifitransfer.base.BaseActivity;
import com.whoisaa.wifitransfer.bean.ConnectedInfo;
import com.whoisaa.wifitransfer.bean.FileInfo;
import com.whoisaa.wifitransfer.bean.Header;
import com.whoisaa.wifitransfer.ui.adapter.CommonAdapter;
import com.whoisaa.wifitransfer.ui.adapter.ViewHolder;
import com.whoisaa.wifitransfer.utils.AppUtils;
import com.whoisaa.wifitransfer.utils.L;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @Description 发文件
 * @Author AA
 * @DateTime 16/4/19 上午11:46
 */
public class SendActivity extends BaseActivity {

    @Bind(R.id.ll_send_progress)
    LinearLayout progressLayout;
    @Bind(R.id.lv_send_connected)
    ListView mListView;
    private CommonAdapter<ConnectedInfo> mAdapter;
    private List<ConnectedInfo> mConnectedInfos = new ArrayList<>();

    private WifiTools mWifiTools;
    private WifiConfiguration mWifiConfiguration;
    private ServerReceiver mServerReceiver;
    private WifiServerThread mServerThread;

    public static List<String> mSelectedFiles = new ArrayList<>();

    public static final String KEY_CHOOSEFILES = "choose_files";
    private static final int REFRESH_CONNECTED_LIST = 2023;
    private static final int REFRESH_SENT_PROGRESS = 2024;
    private static final String TYPE_WIFI = "WIFI";
    private static final String EXTRA_INFO_UNKNOW = "<unknown ssid>";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);
        ButterKnife.bind(this);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        mWifiTools.closeWifiAp(mWifiConfiguration);
    }

    private void init() {
        mSelectedFiles = getIntent().getStringArrayListExtra(KEY_CHOOSEFILES);
        mWifiTools = new WifiTools(this);
        mAdapter = new CommonAdapter<ConnectedInfo>(this, mConnectedInfos, R.layout.item_connected_list) {
            @Override
            public void convert(ViewHolder holder, final ConnectedInfo item) {
                holder.setText(R.id.tv_item_connected_ip, item.getMobileModel() + item.getIpAddress());
                holder.getView(R.id.btn_item_connected_send).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(mServerThread != null) {
                            mServerThread.send();
                            toast("正在发送...");
                        }
                    }
                });
            }
        };
        mListView.setAdapter(mAdapter);
        openWifiAp();
    }

    @OnClick(R.id.btn_send)
    public void send() {
//        if(mServerThread != null) {
//            mServerThread.send();
//            toast("正在发送...");
//        }
    }

    @OnClick(R.id.btn_send_all)
    public void sendFile() {

//        toast("等待连接...");
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_CONNECTED_LIST:
                    mAdapter.notifyDataSetChanged();
                    break;

                case REFRESH_SENT_PROGRESS:


                    break;

                default:
                    toast(msg.obj.toString());
                    break;
            }

        }
    };

    //创建Wi-Fi热点
    public void openWifiAp() {
        mWifiConfiguration = mWifiTools.getWifiApConfig(WifiTools.WIFI_NAME, WifiTools.WIFI_NONE_PWD, WifiTools.NONE);
        if (mWifiTools.openWifiAp(mWifiConfiguration)) {
            Toast.makeText(this, "创建成功", Toast.LENGTH_SHORT).show();
            startServerThread();

//            registerReceiver();

        } else {
            Toast.makeText(this, "创建失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取文件头部信息
     * @return
     */
    private Header getHeader() {
        Header header = new Header();
        List<FileInfo> fileInfos = new ArrayList<>();
        //手机型号
        header.setMobileModel(AppUtils.getMobileModel());
        //文件总数
        int fileTotalCount = mSelectedFiles.size();
        header.setFileTotalCount(fileTotalCount);
        //文件名::文件大小
        for(String selectedFile : mSelectedFiles) {
            int fileSize = 0;
            try {
                InputStream fileInputStream = new FileInputStream(new File(selectedFile));
                fileSize = fileInputStream.available();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileInfos.add(new FileInfo(selectedFile, fileSize));
        }
        header.setFileInfos(fileInfos);
        return  header;
    }


    /**
     * 开启发送端线程
     */
    private void startServerThread() {
        if(mServerThread == null) {
            mServerThread = new WifiServerThread(this, getHeader(), mHandler, new IServerConnectionListener() {
                @Override
                public void onSuccess(List<ConnectedInfo> connectedInfos) {
                    if(!isEmpty(connectedInfos)) {
                        mConnectedInfos.clear();
                        for(ConnectedInfo connectedInfo : connectedInfos) {
                            if(connectedInfo != null) {
                                mConnectedInfos.add(connectedInfo);
                                mHandler.sendEmptyMessage(REFRESH_CONNECTED_LIST);
                            }
                        }
                    }
                }

                @Override
                public void onFailure(Exception e) {

                }
            });
        }
        mServerThread.start();
    }

    /**
     * 注册Wi-Fi网络状态监听器
     */
    private void registerReceiver() {
        if (mServerReceiver == null) {
            mServerReceiver = new ServerReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(mServerReceiver, intentFilter);
    }

    /**
     * 反注册Wi-Fi网络状态监听器
     */
    private void unregisterReceiver() {
        unregisterReceiver(mServerReceiver);
    }

    /**
     * 发送端Wi-Fi接收器
     */
    private class ServerReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null
                    && networkInfo.isConnected()
                    && networkInfo.isConnectedOrConnecting()
                    && networkInfo.getTypeName().equals(TYPE_WIFI)
                    && !networkInfo.getExtraInfo().equals(EXTRA_INFO_UNKNOW)) {
                //连接成功
                WifiTools wifiTools = new WifiTools(context);
                while (true) {
                    try {
                        Thread.currentThread();
                        Thread.sleep(100);
                        DhcpInfo dhcpInfo = wifiTools.getDhcpInfo();
                        if(dhcpInfo.gateway != 0) {
                            L.error("连接成功 - " + dhcpInfo.gateway);
                            //开启发送端线程
                            startServerThread();
                            unregisterReceiver();
                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
